package com.hmkj.core.service.user.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.common.utils.OrderNoUtils;
import com.hmkj.core.api.ninepai.RpmUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.amount.CashMapper;
import com.hmkj.core.mapper.user.UserBankMapper;
import com.hmkj.core.mapper.user.UserMapper;
import com.hmkj.core.po.amount.Cash;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.user.UserBank;
import com.hmkj.core.service.user.UserBankService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户绑卡记录业务相关Service接口实现<br>
 *
 * @author donfy
 * @ClassName: UserBankServiceImpl
 * @date 2017-08-25 04:51:01
 */
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class UserBankServiceImpl implements UserBankService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserBankMapper userBankMapper;
    @Resource
    private CashMapper cashMapper;

    @Override
    public GenericMapper<UserBank, Integer> _getMapper() {
        return userBankMapper;
    }

    @Override
    public void doVerify(UserBank userBank) throws Exception {
        UserBank bank = userBankMapper.selectByPrimaryKey(userBank.getId());
        if (bank == null) {
            throw new BussinessException("审核记录不存在");
        }
        bank.setRemark(userBank.getRemark());
        userBankMapper.updateByPrimaryKeySelective(bank);
    }

    @Override
    public void add(final UserBank bank) {
        int i = userBankMapper.selectCount(new UserBank(b -> {
            b.setUserId(bank.getUserId());
            b.setBankNo(bank.getBankNo());
            b.setDelFlag(UserBank.DELFLAG.NORMAL.code);
        }));
        if (i > 0) throw new BussinessException("当前银行卡已存在");

        int i2 = userBankMapper.insert(bank);
        if (i2 != 1) throw new BussinessException("银行卡添加失败");
    }

    @Override
    public void del(Integer id, Integer userId) {
        //校验当前银行卡是否有提现待审核
        UserBank userBank = userBankMapper.selectByPrimaryKey(id);
        int c = cashMapper.selectCount(new Cash(cash -> {
            cash.setBankNo(userBank.getBankNo());
            cash.setStatus(Cash.STATUS.T2.code);
            cash.setUserId(userId);
            cash.setDelFlag(Cash.DELFLAG.NORMAL.code);
        }));
         if (c > 0){
            throw new BussinessException("当前银行卡有提现待审核,暂时无法删除");
        }
        int i = userBankMapper.selectCount(new UserBank(u -> {
            u.setId(id);
            u.setUserId(userId);
        }));
        if (i != 1) throw new BussinessException("删除失败");
        int i2 = userBankMapper.updateByPrimaryKeySelective(new UserBank(u -> {
            u.setId(id);
            u.setDelFlag(UserBank.DELFLAG.DELETED.code);
        }));
        if (i2 != 1) throw new BussinessException("删除失败");
    }

    @Override
    public void doBindCard9pai(Integer userId, String phone, String cardNo, String cardType, String expireDate, String cvn2) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) throw new BussinessException("查询用户信息失败");

        if (StrUtil.isBlank(user.getIdCard()) || StrUtil.isBlank(user.getRealName()))
            throw new BussinessException("请先进行实名认证");

        // 调用九派接口
        Map<String, String> retMap = RpmUtils.doBindCard(userId, OrderNoUtils.getSerialNumber(), user.getIdCard(), user.getRealName(), phone, cardNo, cardType, expireDate, cvn2);

        if (!"IPS00000".equals(retMap.get("rspCode"))) {
            throw new BussinessException(retMap.get("rspMessage"));
        }
        // 保存银行卡信息
        if (userBankMapper.insert(new UserBank(t -> {
            t.setCvn2(cvn2);
            t.setCardType(cardType);
            t.setExpireDate(expireDate);
            t.setMobile(phone);
            t.setBankName(retMap.get("bankName"));
            t.setBankCode(UserBank.outCode2innerCode4nInepay(retMap.get("bankAbbr")));
            t.setContractId(retMap.get("contractId"));
            t.setBankNo(cardNo);
            t.setRealName(user.getRealName());
            t.setIdCard(user.getIdCard());
            t.setUserId(userId);
            t.setStatus(UserBank.STATUS.T3.code);
        })) != 1) throw new BussinessException("保存用户银行卡信息失败");
    }

    @Override
    public void doUnBindCard(Integer userId, Integer bankId) {

        UserBank bank = userBankMapper.selectByPrimaryKey(bankId);
        if (bank == null) throw new BussinessException("银行卡不存在");
        if (bank.getUserId().intValue() != userId.intValue()) throw new BussinessException("您无权进行该操作");

        if (StrUtil.isNotBlank(bank.getContractId())){
            // 调用九派接口
            Map<String, String> retMap = RpmUtils.doUnbindCard(userId, bank.getContractId());

            if (!"IPS00000".equals(retMap.get("rspCode"))) {
                throw new BussinessException(retMap.get("rspMessage"));
            }
        }

        int i2 = userBankMapper.updateByPrimaryKeySelective(new UserBank(u -> {
            u.setId(bankId);
            u.setDelFlag(UserBank.DELFLAG.DELETED.code);
        }));
        if (i2 != 1) throw new BussinessException("删除失败");
    }
}
